/**
 *  This file is part of AugeasWH.
 *
 *  AugeasWH. is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  AugeasWH. is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with AugeasWH.  If not, see <http://www.gnu.org/licenses/>.
 */

package cz.fit.vutbr.pis2012.augeaswh.control.authentication;

import java.io.IOException;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import com.sun.faces.config.DbfFactory.FacesSchema;

import cz.fit.vutbr.pis2012.augeaswh.managers.UserManager;
import cz.fit.vutbr.pis2012.augeaswh.persistence.User;
import cz.fit.vutbr.pis2012.augeaswh.utils.FacesUtils;

@ManagedBean
@SessionScoped
public class AuthenticationBean {

	@EJB
	private UserManager userManager;
	private String userName;
	private String userPassword;
	private User loggedUser;

	/**
	 * Konstruktor inicializuje vnutorne premenne.
	 */
	public AuthenticationBean() {
		userName = "";
		userPassword = "";
		loggedUser = null;
	}

	/**
	 * Vrati aktualne nastavene uzivatelske heslo
	 * 
	 * @return Uzivatelske heslo
	 */
	public String getUserName() {
		return userName;
	}

	/**
	 * Nastavi hodnotu uzivatelskeho hesla
	 * 
	 * @param userName
	 *            uzivatelske heslo
	 */
	public void setUserName(String userName) {
		this.userName = userName;
	}

	/**
	 * Vrati hodnotu uzivatelskeho hesla
	 * 
	 * @return uzivatelske heslo
	 */
	public String getUserPassword() {
		return userPassword;
	}

	/**
	 * Nastavi hodnotu uzivatelskeho hesla
	 * 
	 * @param password
	 *            uzivatelske heslo
	 */
	public void setUserPassword(String password) {
		this.userPassword = password;
	}

	/**
	 * Pokusi sa autentifikovat uzivatele pomocou udajou ktore su nastavene
	 * 
	 * @return navigation rule retazec
	 */
	public String doAuthentication() {
		loggedUser = userManager.getUserByNameAndPassword(userName,
				userPassword);
		if (loggedUser == null) {
			System.out.println("Login Failed");
			FacesUtils.addFacesMessage("loginForm", "Invalid credentials");
		}
		FacesUtils.setSessionObject("loggedUser", (Object) loggedUser);
		return isUserLogged() ? "auth_success" : "auth_failed";
	}

	/**
	 * Overi ci je uzivatel nalogovany. Uzivatel je nalogovany pokial je
	 * nainicializovany vnutorny objekt uzivatela. Vnutorny objekt uzivatela sa
	 * inicializuje pri uspesnom autentifikovani.
	 * 
	 * @see doAuthentication
	 * @return true ak je nalogovany; false inak
	 */
	public boolean isUserLogged() {
		return loggedUser != null;
	}

	/**
	 * Vrati nalogovaneho uzivatela. Pokial uzivatel nie jen nalogovany vyhodi
	 * vynimku
	 * 
	 * @return nalogovany uzivatel
	 * @throws IllegalStateException
	 *             ked uzivatel nie je nalogovany
	 */
	public User getLoggedUser() throws IllegalStateException {
		if (loggedUser == null) {
			throw new IllegalStateException("User not logged");
		}
		return loggedUser;
	}

	/**
	 * Odhlasi uzivatela
	 * 
	 * @return navigation rule retazec
	 * @throws IOException
	 */
	public String doLogout() throws IOException {
		ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
		HttpSession session = (HttpSession) ectx.getSession(false);
		session.invalidate();

		return "/faces/login.xhtml?faces-redirect=true";
	}

	/**
	 * Otestuje ci ma prihlaseny uzivatel pravo na danu akciu
	 * 
	 * @param rightId pravo id
	 * @return true ak ma pravo, false v opacnom pripade
	 * @see AccessRightManager.translateRightIdToAccessRight
	 */
	public boolean hasRightsToPerformAction(int rightId) {
		if (isUserLogged() == false)
			return false;
		return AccessRightManager.hasUserRightToPerformAction(loggedUser,
				AccessRightManager.translateRightIdToAccessRight(rightId));
	}
}